import { login } from "@/network/api/login.js";
import { setToKen, setUserName, getUserName } from "../../utils/app";

const state = {
  userName: getUserName() || "",
  token: ""
};

const mutations = {
  SET_ADMIN_NAME(state, value) {
    state.userName = value;
    setUserName(value);
  },
  SET_ADMIN_TOKEN(state, value) {
    state.token = value;
    setToKen(value);
  }
};

//对于vuex中存储的数据可以进行异步处理 ，异步处理的时候需要使用promise  也可以进行同步处理  同步处理的时候只需要通过参数调用mutations即可
const actions = {
  loginStore(content, data) {
    return new Promise((resolve, reject) => {
      login(data)
        .then(result => {
          console.log(result);
          let data = result.data.data;

          content.commit("SET_ADMIN_NAME", data.username);
          content.commit("SET_ADMIN_TOKEN", data.token);
          resolve(result);
        })
        .catch(err => {
          reject(err);
        });
    });
  }
};

export default {
  namespaed: true,
  state,
  mutations,
  actions
};
